package com.ruoyi.industry.utils;

import com.ruoyi.common.core.utils.DateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class EntrustUtil {

    public void exportWord(StringBuffer stringBuffer, HttpServletResponse response) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            //编号
            dataMap.put("text", stringBuffer.toString());

            //Configuration 用于读取ftl文件
            Configuration configuration = new Configuration(new Version("2.3.31"));
            configuration.setDefaultEncoding("utf-8");

            configuration.setDirectoryForTemplateLoading(new File("/home/ruoyi/config/ftl"));

            //输出文档路径及名称
            File outFile = File.createTempFile("build" + DateUtils.dateTimeNow(), ".doc");

            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("weituo.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            template.process(dataMap, out);
            out.close();


            InputStream fis = new BufferedInputStream(new FileInputStream(outFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.setContentType("multipart/form-data");
            // 设置response的Header
            response.setHeader("Content-Disposition",
                    "attachment; filename=build" + DateUtils.dateTimeNow() + ".doc");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
